/** @file
 *
 *  lidar209 3D LIDAR data input classes
 *
 *    These classes provide raw lidar209 LIDAR input packets from
 *    either a live socket interface or a previously-saved PCAP dump
 *    file.
 *
 *  Classes:
 *
 *     lidar209::Input -- base class for accessing the data
 *                      independently of its source
 *
 *     lidar209::InputSocket -- derived class reads live data from the
 *                      device via a UDP socket
 *
 *     lidar209::InputPCAP -- derived class provides a similar interface
 *                      from a PCAP dump file
 */

#ifndef __lidar209_INPUT_H
#define __lidar209_INPUT_H


#include <rclcpp/rclcpp.hpp>
#include <memory>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <pcap.h>
#include <netinet/in.h>

#include <lidar209_msgs/msg/lidar209_packet.hpp>
#include <lidar209_msgs/msg/lidar209_packet_ch72.hpp>
#include <lidar209_msgs/msg/lidar209_packet_ch88.hpp>


namespace lidar209_driver
{
constexpr uint16_t DATA_PORT_NUMBER = 2368;     // default data port
constexpr uint16_t POSITION_PORT_NUMBER = 8308; // default position port

/** @brief lidar209 input base class */
class Input
{
public:
  explicit Input(rclcpp::Node * private_nh, const std::string & devip, uint16_t port);
  virtual ~Input() {}

//  virtual int getPacket(lidar209_msgs::msg::lidar209Packet *pkt,
//                        const double time_offset) = 0;
//  virtual int getPacket(lidar209_msgs::msg::lidar209Packet_CH72 *pkt,
//                        const double time_offset) = 0;

  virtual int getPacket(lidar209_msgs::msg::Lidar209PacketCH88 *pkt,
                        const double time_offset) = 0;

protected:
  rclcpp::Node * private_nh_;
  std::string devip_str_;
  uint16_t port_;
  int ip1_,ip2_;
};

class InputSocket final : public Input
{
public:
  explicit InputSocket(
    rclcpp::Node * private_nh,
    const std::string & devip, uint16_t port, bool gps_time);
  ~InputSocket() override;

  int getPacket(
    lidar209_msgs::msg::Lidar209PacketCH88 * pkt,
    const double time_offset) override;
  void setDeviceIP(const std::string & ip);

private:
  int sockfd_;
  in_addr devip_{};
  bool gps_time_;

};


class InputPCAP final : public Input
{
public:
  explicit InputPCAP(
    rclcpp::Node * private_nh,
    const std::string & devip,
    uint16_t port,
    double packet_rate,
    const std::string & filename,
    bool read_once,
    bool read_fast,
    double repeat_delay);
  ~InputPCAP() override;

  int getPacket(
    lidar209_msgs::msg::Lidar209PacketCH88 * pkt,
    const double time_offset) override;
  void setDeviceIP(const std::string & ip);

private:
  rclcpp::Rate packet_rate_;
  std::string filename_;
  pcap_t * pcap_;
  bpf_program pcap_packet_filter_{};
  char errbuf_[PCAP_ERRBUF_SIZE]{};
  bool empty_;
  bool read_once_;
  bool read_fast_;
  double repeat_delay_;
};

} // lidar209_driver namespace

#endif // __lidar209_INPUT_H
